$(function(){
    findProjectName();
    $.extend($.fn.validatebox.defaults.rules, {
        isNumber: {
            validator: function (value, param) {
                return /^-?\d+\.?\d*$/.test(value);
            },
            message: '请输入正确的数字!'
        }
    });

    getTechnology();
    $('#technologydglist').datagrid({
        url: "",
        method: "post",
        striped: true,
        singleSelect:true,
        rownumbers: true,
        loadMsg: "努力加载中...",
        width:'100%',
        height:'320px',
        fitColumns: true,//是否自动填充适合屏幕
        pagination: true,//是否显示底部分页工具栏
        pageSize: 100,
        pageList: [100, 110, 120],
        showFooter: true,
        autoRowHeight: false,
        columns: [[
            {field: 'id',hidden:'true'},
            {field: 'sequenceNumber' ,title: '序号', sortable: true, width:50, align: "center"},
            {field: 'productionProcesses', title: '工序', sortable: true, width:100, align: "center"},
            {field: 'processContent', title: '工艺内容', sortable: true, width: 300, align: "center"},
            {field: 'productionQuantity', title: '生产数量', sortable: true, width: 100, align: "center"},
            {field: 'estimateTime', title: '预估工时（H)', sortable: true, width: 100, align: "center"},
            {field: 'operator', title: '操作员', sortable: true, width: 100, align: "center"},
            {field: '7',hidden:'true', title: '下工段接收确认', sortable: true, width: 100, align: "center"},
            {field: '8', hidden:'true',title: '备注', sortable: true, width: 100, align: "center"}

        ]],
        toolbar: [

        ],
    });
    $('#technologydglist').datagrid('getPager').pagination({//分页栏下方文字显示
        beforePageText: '第',
        afterPageText: '页，总共 {pages}页',
        displayMsg: '当前显示从第{from}条到{to}条 共{total}条记录',
    });
});
function findProjectName(){
    $.ajax({
        type: "GET",
        url: "findProjectName",
        timeout: 20000,
        dataType: "json",
        cache: false,
        success: function(data){
            $("#showProjectId").combobox('loadData',data);
        }
    });
}
function openAddTechnologyWin(){
    findProjectName();
    var val = $("#showProjectId").combobox('getData');
    $("#showProjectId").combobox('select', val[0].id);
    $("#showWorkOrderId").val(0);
    $("#addTechnologyWin").show().window("open");
}
//确认添加项目
function addProject(){

            $.messager.confirm('确认', '您确认添加吗？', function (r) {
                if (r) {
                    $.ajax({
                        type: "POST",
                        url: "addProductionProject",
                        data: $("#addProjectForm").serialize(),
                        timeout: 20000,
                        dataType: "json",
                        cache: false,
                        success: function (data) {
                            if (data.msg == "success") {
                                $.messager.alert("提示", "添加成功！", "info", function () {
                                    $('#addProjectForm').form("reset");
                                    cancelWin('addProjectWin', 'addProjectForm');
                                    $("#showProjectId").val(data.project.id);
                                    console.info($("#showProjectId").val())
                                    $("#showProjectName").textbox("setValue", data.project.projectName);
                                    $("#showPartsName").textbox("setValue", data.project.partsName);
                                    $("#showChartNumber").textbox("setValue", data.project.chartNumber);
                                    $("#showOderNumber").textbox("setValue", data.project.oderNumber);
                                    $("#dglist").datagrid("load");
                                    $("#addTechnologyWin").show().window("open");
                                });
                            } else {
                                $.messager.alert("警告", "添加失败！", "info", function () {

                                })
                            }
                        },
                        error: function () {
                            $.messager.alert("提示", "出现了不可预知的错误，请重新操作！");
                        }
                    })
                }
            });
}
//自动生成添加的按钮的ID的方法
function setBtnId(data){
    $("#btnId").val("btn"+(data.length+1));
}
//从数据库动态加载工艺名称
function getTechnology(){
    $.ajax({
        url: "getTechnologyList",
        type: "post",
        dataType: "json",
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            setBtnId(data);
            addButton(data);

        },
        error: function () {
            $.messager.alert("警告", "加载工艺名称失败！", "error")
        },
    })

};

//在panel动态内添加按钮
function addButton(data){
    for(var i=0;i<data.length;i++){
        $("#btnpanel").append("<a id='"+data.btns[i].btnId+"'   class='easyui-linkbutton'>"+data.btns[i].technologyName+"</a>&nbsp;")
        $("#btnpanel").append("<input type='hidden' value='"+data.btns[i].technologyName+"' id='"+data.btns[i].btnId+"-2'>&nbsp;&nbsp;")
        addFun(data.btns[i].btnId);
    }
    $("#btnpanel").append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a id='deleteTechnology'  iconCls='icon-remove'   class='easyui-linkbutton'>删除</a>&nbsp;&nbsp;")
    addDeleteFun("deleteTechnology");
    // $("#btnpanel").append("&nbsp;&nbsp;<a id='addBtn' hidden='true' iconCls='icon-add'   class='easyui-linkbutton'>添加工艺按钮</a>")
    // addBtnFun("addBtn");
    $.parser.parse("#btnpanel");

}

//为工艺按钮添加事件
function addFun(id){
    $("#"+id).click(function(){
        if($("#showProjectName").val()==""||$("#showPartsName").val()==""||$("#showChartNumber").val()==""||$("#showOderNumber").val()==""){
            $.messager.alert("提示","请先填写项目名称、零件名称、图号、订单数量后再进行工艺添加。");
            return;
        }
        $("#productionProcesses").textbox("setValue",$("#"+id+"-2").val());

        $("#clickBtnWin").show().window("open");
    });
}

function canceladdTechnologyWin() {
    $('#technologydglist').datagrid('load',{workOrderId: 0});
    $("#showWorkOrderId").val("");
    $("#showProjectId").combobox('enable');
    $("#showPartsName").textbox("setValue","");
    $('#showPartsName').textbox('textbox').attr('disabled',false);
    $("#showChartNumber").textbox("setValue","");
    $('#showChartNumber').textbox('textbox').attr('disabled',false);
    $("#showOderNumber").textbox("setValue","");
    $('#showOderNumber').textbox('textbox').attr('disabled',false);
    $("#updateTechnology").remove();
    $("#addTechnologyWin").window("close");

    $("#dglist").datagrid('reload');

}

//确认添加工艺
function addTechnology() {
    $('#clickBtnForm').form('submit', {
        onSubmit:function() {
            if(!$(this).form('enableValidation').form('validate')){
                return $(this).form('enableValidation').form('validate');
            }

    var productionProcesses = $("#productionProcesses").val();
    var sequenceNumber = $("#sequenceNumber").val();
    var processContent = $("#processContent").val();
    var productionQuantity = $("#productionQuantity").val();
    var estimateTime = $("#estimateTime").val();
    var operator = $("#operator").val();

    var projectId=$('#showProjectId').combobox('getValue');
    var workOrderId= $("#showWorkOrderId").val();
    var showPartsName = $("#showPartsName").val();
    var showChartNumber = $("#showChartNumber").val();
    var showOderNumber = $("#showOderNumber").val();
    $.ajax({
        url: "addProcessFlow",
        type: "POST",
        data: {
            projectId: projectId,
            productionProcesses: productionProcesses,
            sequenceNumber: sequenceNumber,
            processContent: processContent,
            productionQuantity: productionQuantity,
            estimateTime: estimateTime,
            operator: operator,
            workOrderId:workOrderId,
            showPartsName: showPartsName,
            showChartNumber: showChartNumber,
            showOderNumber: showOderNumber
        },
        timeout: 20000,
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.msg == "success") {
                $.messager.alert("提示", "添加工序成功！", "info", function () {
                    cancelWin("clickBtnWin", "clickBtnForm");
                    $('#technologydglist').datagrid({url: 'findProcessFlowByWorkOrderId'});
                    $('#technologydglist').datagrid('load', {workOrderId: data.workOrder.id});
                    $("#showWorkOrderId").val(data.workOrder.id);

                })
            } else {
                $.messager.alert("提示", data.result, "info", function () {
                    cancelWin("clickBtnWin", "clickBtnForm");
                })

            }
        }, error: function () {
            $.messager.alert("提示", "出现了不可预知的错误，请重新操作！");
        }
    })
}
})
}


function exportFTechnologicalProcess(){
    // window.location.href=
    window.open("export?workOrderId="+$.getSingleRecord("dglist").id);

}

//打印的方法
function exportTechnologicalProcess(){
    window.open("export?workOrderId="+$("#showWorkOrderId").val());
}


//为删除按钮添加删除事件(批量删除)
function addDeleteFun(id){
    $("#"+id).click(function(){
        var ids=$.getManyRecords("technologydglist");

        $.messager.confirm('确认', '您确认想要删除记录吗？', function (r) {
            if (r) {
                $.ajax({
                    type: "POST",
                    url: "deleteProcessFlow",
                    data: {ids: ids},
                    timeout: 20000,
                    dataType: "json",
                    cache: false,
                    success: function (data) {
                        if (data.msg == "success") {
                            $.messager.alert("提示", "删除成功！","info",function () {
                                $('#technologydglist') .datagrid('load');

                            })
                        } else {
                            $.messager.alert("提示", "删除失败！","info");
                        }

                    },
                    error: function () {
                        $.messager.alert("提示", "出现了不可预知的错误，请重新操作！");
                    }
                })
            }
        });
    });
}

//为添加工艺这个按钮添加事件
function addBtnFun(id){
    $("#"+id).click(function(){
        openAddBtnWin();
    });
}